package org.daoImpl;

import org.dao.ThreadDao;
import org.model.Thread;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import java.util.List;

/**
 * Created by tedzy on 2015/5/14.
 * Thread Dao Impl
 */
public class ThreadDaoImpl extends HibernateDaoSupport implements ThreadDao{
    @Override
    public int newThread(String title) {
        Thread t = new Thread();
        t.setTitle(title);
        this.getHibernateTemplate().save(t);
        return t.getId();
    }

    @Override
    public boolean addFloor(int threadId, int floorId) {
        Thread t;
        List list = this.getHibernateTemplate().find("from Thread where id=?", threadId);
        if(list.size() >= 1){
            t = (Thread)list.get(0);
        }else{
            return false;
        }

        String newFloorStr = t.getFloorid();
        if(newFloorStr==null||newFloorStr.equals("")){
            t.setFloorid("" + floorId);
        }else {
            t.setFloorid(newFloorStr + "," + floorId);
        }
        this.getHibernateTemplate().update(t);
        return true;
    }

    @Override
    public Thread readThread(int id) {
        Thread t;
        List list = this.getHibernateTemplate().find("from Thread where id=?", id);
        if(list.size() >= 1){
            t = (Thread) list.get(0);
        }else{
            t = null;
        }
        return t;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Thread> getThreads() {
        return (List<Thread>) this.getHibernateTemplate().find("from Thread order by post_time desc");
    }
}
